package com.chen.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.commons.Result;
import com.chen.entity.Book;
import com.chen.mapper.BookMapper;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/book")
@SuppressWarnings("all")
public class BookController {
    //依赖注入
    @Resource
    BookMapper bookMapper;


    //    新增
    @PostMapping
    public Result<?> save(@RequestBody Book book) {

       bookMapper.insert(book);
        return Result.success();

    }

    //更新
    @PutMapping
    public Result<?> update(@RequestBody Book book) {
        bookMapper.updateById(book);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id){
        return Result.success(bookMapper.selectById(id));
    }
    //删除
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        bookMapper.deleteById(id);
        return Result.success();
    }

    //    查询
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,  //页号
                              @RequestParam(defaultValue = "10") Integer pageSize, //一页展示的数量
                              @RequestParam(defaultValue = "") String search) {

//        模糊查询
        LambdaQueryWrapper<Book> warapper = Wrappers.<Book>lambdaQuery().like(Book::getName, search);
        if (StrUtil.isBlank(search)) {
            warapper.like(Book::getName, search);
        }
        Page<Book> userPage =bookMapper.selectPage(new Page<>(pageNum, pageSize), warapper);
        return Result.success(userPage);

    }

    //批量删除
    @PostMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestBody List<Integer> ids){
        bookMapper.deleteBatchIds(ids);
        return Result.success();
    }

}
